package com.siruier.boss.ui.viewmodel

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.siruier.boss.R
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.OrderDetailBean
import com.siruier.boss.common.formatPrice
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.base.BaseViewModel
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.helper.pay
import com.siruier.boss.ui.helper.payChannel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.math.BigDecimal

class OrderViewModel : BaseViewModel() {

    val handSuccess: MutableLiveData<String> = MutableLiveData()

    private var orderCountDownJob: Job? = null

    fun handOrderClick(context: Context, orderDetailBean: OrderDetailBean, viewId: Int?) {
        when (viewId) {
            R.id.textOrderButtonPay -> orderPay(context, orderDetailBean)
            R.id.textOrderButtonCancel -> orderCancel(context, orderDetailBean)
        }
    }

    private fun orderPay(context: Context, orderDetailBean: OrderDetailBean) {
        launchUI({
            val activity = (context as BaseActivity<*>)
            var discount = BigDecimal.ZERO
            if (orderDetailBean.type == 2 && orderDetailBean.goodsType in 2..3) {
                discount = mallApi.discount(null, orderDetailBean.orderSn, null).toData()?.discount ?: BigDecimal.ZERO
            }
            val payChannel = activity.payChannel(orderDetailBean.orderPrice, discount)
            payChannel.orderSn = orderDetailBean.orderSn
            // 支付
            activity.pay(payChannel)
        }, ApiObserver(context) {
            if (it == true) {
                handSuccess.value = ""
            }
        })
    }

    private fun orderCancel(context: Context, orderDetailBean: OrderDetailBean) {
        context.showAlertDialog {
            message(message = "确定取消该订单吗?")
            negativeButton { }
            positiveButton {
                launchUI({
                    mallApi.orderCancel(orderDetailBean.orderSn).toData()
                }, ApiObserver(context) {
                    handSuccess.value = ""
                })
            }
        }
    }

    fun cancelOrderCountDownJob() = orderCountDownJob?.cancel()

    fun orderCountDown(ramainSeconds: Int, listener: (Int) -> Unit) {
        listener.invoke(ramainSeconds)
        orderCountDownJob = viewModelScope.launch {
            repeat(ramainSeconds) { i ->
                delay(1000L)
                listener.invoke(ramainSeconds - i)
            }
        }
    }

}